const goods = require('../db/goods')
const {writeFileerror} = require('../utlis/utlis')
const {resinfo} = require('../utlis/utlis')

module.exports ={

    // 获取所有商品数据
    goodslist:async(req,res)=>{
      let {page} = req.params
      let goodslist = await goods.find().skip((page-1)*12).limit(12)
       if(goodslist.length){
        resinfo(res,0,'数据获取成功',{goodslist})
      }else{
        resinfo(res,1,'数据获取失败')
      }
    },

    // 根据id获取商品的详情数据
    goodsdatail:async(req,res)=>{
       let {id} = req.params
       let goodsdatail 
       try{
            goodsdatail = await goods.find({
                _id:id
            })
       }catch(err){
        writeFileerror(err)
        resinfo(res,3,'请求错误！请刷新后重试')
        return
       }
       if(goodsdatail.length){
        let goodsdata = goodsdatail[0]
        resinfo(res,0,'详情数据获取成功',{goodsdata})
       }else{
        resinfo(res,2,'详情数据获取失败')
       }

    },

    // 分页商品获取
    list:async(req,res)=>{
      let {page,pagesize} = req.params
      let total = await goods.count()
      let totalPage = Math.ceil(total/pagesize)

      let goodslist = await goods.find().skip((page-1)*pagesize).limit(pagesize)
      resinfo(res,0,'数据获取成功',{
        total,
        totalPage,
        pagesize,
        page,
        goodslist
      })
    }
}